import React, { useState, useEffect } from 'react';
import { IPublicModelPluginContext } from '@alilc/lowcode-types';
import { Select, Input } from '@alifd/next';
import './index.scss';
export interface IProps {
  project: any;
}

const deviceMap: any = {
  "iPhone6": "375",
  "iPhoneX": "414",
  "pc": "1200",
  "custom": ''
};

function DeviceSelected(props: IProps) {
  const { project } = props;
  const Option = Select.Option;
  const [action, SetAction] = useState('iPhone6');
  const [canvasWidth, setCanvasWidth] = useState(deviceMap[action]);
  const [customValue, setCustomValue] = useState(deviceMap[action]);
  const onChange = function(value: string) {
    SetAction(value);
    setCustomValue(deviceMap[value] || deviceMap[action]);
    deviceMap[value] && setCanvasWidth(deviceMap[value]);
  };
  const customInputChange = (value: string|number) => {
    setCustomValue(+value);
  };
  const customInputBlur = () => {
    setCanvasWidth(customValue);
  }
  const setCanvas = () => {
    project.simulatorHost && project.simulatorHost.set('deviceStyle', {
      canvas: { width: `${canvasWidth}px`, backgroundColor: 'red', margin: 'auto', boxShadow: '0 0 8px 2px #999' },
      viewport: { width: `${canvasWidth}px` }
    });
  }
  useEffect(setCanvas, [canvasWidth]);
  useEffect(() => {
    project.onSimulatorRendererReady(() => { setTimeout(setCanvas, 1); });
    // project.onSimulatorHostReady(() => { setCanvas(); console.log('onSimulatorHostReady'); });
  }, []);
  // console.log('canvasWidth 2 ', canvasWidth);
  return (
    <div className="plugin-device-select">
      <Select
        id="basic-demo"
        onChange={onChange}
        value={action}
        className="select-container"
      >
        <Option value="iPhone6">iPhone6</Option>
        <Option value="iPhoneX">iPhoneX</Option>
        <Option value="pc">pc</Option>
        <Option value="custom">自定义</Option>
      </Select>
      <Input
        disabled={action !== 'custom'}
        value={customValue}
        onChange={customInputChange}
        onBlur={customInputBlur}
        onPressEnter={customInputBlur}
        addonTextBefore="宽度:"
        addonTextAfter="px"
        size="small"
        style={{ width: 130 }}
        maxLength={4}
      />
    </div>
  );
}
const DeviceSelect = (ctx: IPublicModelPluginContext) => {
  return {
    async init() {
      const { skeleton, project } = ctx;
      skeleton.add({
        area: 'topArea',
        type: 'Widget',
        name: 'device',
        content: <DeviceSelected project={project} />,
        props: {
          align: 'center',
        },
      });
    },
  };
}
DeviceSelect.pluginName = 'DeviceSelect';
DeviceSelect.meta = {
  dependencies: ['EditorInitPlugin'],
};
export default DeviceSelect;